package com.sz.admin.ai.controller.caht;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.sz.admin.ai.factory.chatFactory.ChatHandlerFactory;
import com.sz.admin.ai.factory.chatFactory.entity.dto.ChatDTO;
import com.sz.admin.ai.factory.chatFactory.entity.dto.ChatMessageDTO;
import com.sz.admin.ai.factory.chatFactory.entity.dto.ChatModelDTO;
import com.sz.admin.ai.factory.chatFactory.entity.dto.ChatUserDTO;
import com.sz.admin.ai.factory.chatFactory.handler.ChatHandler;
import com.sz.admin.ai.util.LogAspect;
import com.sz.core.common.entity.ApiResult;
import com.sz.core.util.JsonUtils;
import com.sz.core.util.StringUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.Arrays;
import java.util.Objects;

/**
 * @描述:
 * @Author: TangYuan
 * @Date: 2025/2/27 16:04
 */
@RequestMapping("/ai/message")
@RestController
@CrossOrigin
@AllArgsConstructor
@Log4j2
public class ChatController {
    
    private final ChatHandlerFactory chatHandlerFactory;
    
    @LogAspect
    @PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @SneakyThrows
    public Flux<ServerSentEvent<String>> chat(@RequestBody ChatDTO chat) {
        ApiResult<String> apiResult = parameterJudgment(chat);
        if (Objects.equals(apiResult.code, "9999")) {
            return Flux.just(ServerSentEvent.builder(JsonUtils.toJsonString(apiResult)).event("error").build());
        }
        ChatHandler handler = chatHandlerFactory.getHandler(chat.getChatModel().getModelPlatformName());
        return handler.chat(chat);
    }

    private ApiResult<String> parameterJudgment(ChatDTO chat) {
        ChatUserDTO user = chat.getUser();
        ChatMessageDTO message = chat.getMessage();
        ChatModelDTO chatModel = chat.getChatModel();
        
        if (user == null || message == null || chatModel == null) {
            return ApiResult.error("参数错误");
        }
        if (message.getContent() == null || message.getSessionId() == null) {
            return ApiResult.error("message参数不能为空");
        }
        if (user.getUsername() == null || user.getPassword() == null) {
            return ApiResult.error("用户名密码不能为空");
        }
        if (!user.getUsername().equals("123") || !user.getPassword().equals("123")) {
            return ApiResult.error("用户名密码错误");
        }
        if (chatModel.getModelName() == null || chatModel.getModelPlatformName() == null || chatModel.getContextNumber() == null || chatModel.getMaxTokens() == null || chatModel.getTemperature() == null) {
            return ApiResult.error("chatModel参数不能为空");
        }

        // 设置默认参数
        if (StringUtils.isEmpty(message.getPromptText())) {
            message.setPromptText("""
                    你是一个默认助手，帮助用户解决问题。
                    """);
        }
        if (StringUtils.isEmpty(message.getRole())) {
            message.setRole("USER");
        }
        
        return ApiResult.success();
    }
    
    @GetMapping("/aaaa")
    public String chat() throws NoApiKeyException, InputRequiredException {
        
        Generation gen = new Generation();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("你好，我叫张三，今年18岁，十年后我多少岁")
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey("sk-1ee02e3b0e564d18b289e818f485f763")
                .model("deepseek-r1")
                .messages(Arrays.asList(userMsg))
                // 不可以设置为"text"
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        GenerationResult call = gen.call(param);
        System.out.println("思考过程：");
        System.out.println(call.getOutput().getChoices().get(0).getMessage().getReasoningContent());
        System.out.println("回复内容：");
        System.out.println(call.getOutput().getChoices().get(0).getMessage().getContent());
        
        return JsonUtils.toJsonString(call);
        
    }
}
